<template>
  <div class="checkout-view">
    <div class="header">
      <button class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </button>
      <h1>确认订单</h1>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载订单信息...</p>
    </div>

    <div v-else class="checkout-content">
      <!-- 配送地址 -->
      <div class="section address-section">
        <div class="section-header">
          <h2>配送地址</h2>
          <button class="add-address-btn" @click="showAddressModal = true">
            <i class="fas fa-plus"></i> 新增地址
          </button>
        </div>
        
        <div v-if="addresses.length === 0" class="empty-address">
          <p>暂无配送地址，请先添加地址</p>
        </div>
        
        <div v-else class="address-list">
          <div 
            v-for="address in addresses" 
            :key="address.id"
            :class="{ active: selectedAddressId === address.id }"
            class="address-card"
            @click="selectedAddressId = address.id"
          >
            <div class="address-info">
              <div class="contact">
                <span class="name">{{ address.name }}</span>
                <span class="phone">{{ address.phone }}</span>
              </div>
              <div class="address">{{ address.address }}</div>
            </div>
            <div class="address-actions">
              <button v-if="address.isDefault" class="default-tag">默认</button>
              <i class="fas fa-check-circle" v-if="selectedAddressId === address.id"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- 店铺信息 -->
      <div class="section shop-section">
        <div class="shop-info">
          <div class="shop-name">{{ shopInfo.name }}</div>
          <div class="shop-address">{{ shopInfo.address }}</div>
        </div>
      </div>

      <!-- 商品清单 -->
      <div class="section items-section">
        <h2>商品清单</h2>
        <div class="items-list">
          <div v-for="item in cartItems" :key="item.id" class="item-row">
            <div class="item-image" :style="{ backgroundImage: `url(${item.image})` }"></div>
            <div class="item-info">
              <h3>{{ item.name }}</h3>
              <p class="item-desc">{{ item.description }}</p>
            </div>
            <div class="item-quantity">x{{ item.quantity }}</div>
            <div class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          </div>
        </div>
      </div>

      <!-- 费用明细 -->
      <div class="section price-section">
        <h2>费用明细</h2>
        <div class="price-details">
          <div class="price-row">
            <span>商品总价</span>
            <span>¥{{ subtotal.toFixed(2) }}</span>
          </div>
          <div class="price-row">
            <span>配送费</span>
            <span>¥{{ deliveryFee.toFixed(2) }}</span>
          </div>
          <div class="price-row discount" v-if="discount > 0">
            <span>优惠减免</span>
            <span>-¥{{ discount.toFixed(2) }}</span>
          </div>
          <div class="price-row total">
            <span>实付金额</span>
            <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="section payment-section">
        <h2>支付方式</h2>
        <div class="payment-methods">
          <div 
            v-for="method in paymentMethods" 
            :key="method.id"
            :class="{ active: selectedPaymentMethod === method.id }"
            class="payment-method"
            @click="selectedPaymentMethod = method.id"
          >
            <div class="method-icon">
              <i :class="method.icon"></i>
            </div>
            <div class="method-info">
              <div class="method-name">{{ method.name }}</div>
              <div class="method-desc">{{ method.description }}</div>
            </div>
            <i class="fas fa-check-circle" v-if="selectedPaymentMethod === method.id"></i>
          </div>
        </div>
      </div>

      <!-- 备注 -->
      <div class="section note-section">
        <h2>订单备注</h2>
        <textarea 
          v-model="orderNote" 
          placeholder="请输入订单备注（选填）"
          rows="3"
        ></textarea>
      </div>
    </div>

    <!-- 底部提交栏 -->
    <div class="checkout-footer">
      <div class="price-summary">
        <div class="total-amount">
          <span>实付金额：</span>
          <span class="amount">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
      </div>
      <button 
        class="submit-btn" 
        @click="submitOrder"
        :disabled="!canSubmit || submitting"
      >
        {{ submitting ? '提交中...' : '提交订单' }}
      </button>
    </div>

    <!-- 新增地址模态框 -->
    <div v-if="showAddressModal" class="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>新增地址</h3>
          <button class="close-btn" @click="showAddressModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>联系人</label>
            <input type="text" v-model="newAddress.name" placeholder="请输入联系人姓名">
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input type="tel" v-model="newAddress.phone" placeholder="请输入手机号">
          </div>
          <div class="form-group">
            <label>详细地址</label>
            <textarea v-model="newAddress.address" placeholder="请输入详细地址" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>
              <input type="checkbox" v-model="newAddress.isDefault">
              设为默认地址
            </label>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="showAddressModal = false">取消</button>
          <button class="save-btn" @click="saveAddress">保存</button>
        </div>
      </div>
    </div>

    <!-- 订单提交成功模态框 -->
    <div v-if="showSuccessModal" class="modal">
      <div class="modal-content">
        <div class="modal-body success-content">
          <div class="success-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <h3>订单提交成功！</h3>
          <p>订单号：{{ submittedOrderId }}</p>
          <p>请耐心等待商家接单</p>
        </div>
        <div class="modal-footer">
          <button class="primary-btn" @click="goToOrders">查看订单</button>
          <button class="secondary-btn" @click="goToHome">返回首页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserIdStore } from '@/stores/UserId';
import { selectById as getShopById, type Shop } from '@/http/Shop';
import { insert as createOrder, type Order } from '@/http/Order';
import { message } from '@/utils/message';

interface CartItem {
  id: number;
  name: string;
  description: string;
  price: number;
  image: string;
  quantity: number;
}

interface Address {
  id: number;
  name: string;
  phone: string;
  address: string;
  isDefault: boolean;
}

interface PaymentMethod {
  id: string;
  name: string;
  description: string;
  icon: string;
}

const route = useRoute();
const router = useRouter();
const userIdStore = useUserIdStore();

const loading = ref(true);
const submitting = ref(false);
const showAddressModal = ref(false);
const showSuccessModal = ref(false);
const submittedOrderId = ref('');

// 订单数据
const shopId = ref<number>(0);
const cartItems = ref<CartItem[]>([]);
const shopInfo = ref<Shop>({
  id: null,
  createTime: null,
  updateTime: null,
  relaUserId: null,
  name: null,
  description: null,
  logoAddress: null,
  address: null,
  positionX: null,
  positionY: null,
  phone: null,
  startTime: null,
  endTime: null,
  minOrderAmount: null,
  deliveryFee: null,
  avRating: null,
  avAmount: null,
  monthlyOrderCount: null,
  image: null
});

// 地址相关
const addresses = ref<Address[]>([
  {
    id: 1,
    name: '张先生',
    phone: '138****1234',
    address: '北京市朝阳区建国路88号SOHO现代城A座1001室',
    isDefault: true
  },
  {
    id: 2,
    name: '李女士',
    phone: '139****5678',
    address: '北京市海淀区中关村大街1号科技大厦B座2002室',
    isDefault: false
  }
]);

const selectedAddressId = ref<number>(1);
const newAddress = reactive<Partial<Address>>({
  name: '',
  phone: '',
  address: '',
  isDefault: false
});

// 支付方式
const paymentMethods = ref<PaymentMethod[]>([
  {
    id: 'wechat',
    name: '微信支付',
    description: '推荐使用微信支付',
    icon: 'fab fa-weixin'
  },
  {
    id: 'alipay',
    name: '支付宝',
    description: '支持花呗分期',
    icon: 'fab fa-alipay'
  },
  {
    id: 'cash',
    name: '货到付款',
    description: '送达后现金支付',
    icon: 'fas fa-money-bill-wave'
  }
]);

const selectedPaymentMethod = ref('wechat');
const orderNote = ref('');

// 计算属性
const subtotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0);
});

const deliveryFee = computed(() => {
  return (shopInfo.value.deliveryFee || 500) / 100; // 转换为元
});

const discount = computed(() => {
  // 简单的满减优惠逻辑
  if (subtotal.value >= 50) {
    return 5;
  }
  return 0;
});

const totalPrice = computed(() => {
  return subtotal.value + deliveryFee.value - discount.value;
});

const canSubmit = computed(() => {
  return selectedAddressId.value && 
         selectedPaymentMethod.value && 
         cartItems.value.length > 0 &&
         userIdStore.currentUserId;
});

// 页面初始化
onMounted(() => {
  initCheckout();
});

const initCheckout = async () => {
  loading.value = true;
  
  try {
    // 从路由参数获取数据
    shopId.value = parseInt(route.query.shopId as string);
    const itemsData = route.query.items as string;
    
    if (!shopId.value || !itemsData) {
      message.error('订单信息不完整');
      router.push('/');
      return;
    }
    
    // 解析购物车数据
    cartItems.value = JSON.parse(itemsData);
    
    // 加载店铺信息
    const shopResponse = await getShopById(shopId.value);
    if (shopResponse.data) {
      shopInfo.value = shopResponse.data;
    }
    
    // 确保用户已登录
    if (!userIdStore.currentUserId) {
      userIdStore.restoreFromStorage();
      if (!userIdStore.currentUserId) {
        message.warning('请先登录');
        router.push('/user');
        return;
      }
    }
    
    console.log('✅ 结算页面初始化成功');
  } catch (error: any) {
    console.error('❌ 初始化结算页面失败:', error);
    message.error('加载订单信息失败');
  } finally {
    loading.value = false;
  }
};

// 保存地址
const saveAddress = () => {
  if (!newAddress.name || !newAddress.phone || !newAddress.address) {
    message.warning('请填写完整的地址信息');
    return;
  }
  
  const address: Address = {
    id: Date.now(),
    name: newAddress.name,
    phone: newAddress.phone,
    address: newAddress.address,
    isDefault: newAddress.isDefault || false
  };
  
  // 如果设为默认，取消其他地址的默认状态
  if (address.isDefault) {
    addresses.value.forEach(addr => addr.isDefault = false);
    selectedAddressId.value = address.id;
  }
  
  addresses.value.push(address);
  
  // 重置表单
  Object.assign(newAddress, {
    name: '',
    phone: '',
    address: '',
    isDefault: false
  });
  
  showAddressModal.value = false;
  message.success('地址添加成功');
};

// 提交订单
const submitOrder = async () => {
  if (!canSubmit.value) {
    message.warning('请完善订单信息');
    return;
  }
  
  submitting.value = true;
  
  try {
    const selectedAddress = addresses.value.find(addr => addr.id === selectedAddressId.value);
    
    if (!selectedAddress) {
      message.error('请选择配送地址');
      return;
    }
    
    // 准备订单数据
    const orderData: Partial<Order> = {
      relaUserId: userIdStore.currentUserId,
      relaShopId: shopId.value,
      shopName: shopInfo.value.name,
      shopAddress: shopInfo.value.address,
      userAddress: selectedAddress.address,
      status: 'pending',
      totalAmount: Math.round(subtotal.value * 100), // 转换为分
      discount: Math.round(discount.value * 100),
      actualPayment: Math.round(totalPrice.value * 100)
    };
    
    console.log('📤 提交订单:', orderData);
    
    const response = await createOrder(orderData as Order);
    
    if (response.data) {
      submittedOrderId.value = response.data.id?.toString() || '';
      showSuccessModal.value = true;
      message.success('订单提交成功');
      console.log('✅ 订单提交成功:', response.data);
    } else {
      throw new Error('服务器返回数据为空');
    }
    
  } catch (error: any) {
    console.error('❌ 提交订单失败:', error);
    message.error('提交订单失败: ' + (error.message || '网络错误'));
  } finally {
    submitting.value = false;
  }
};

// 导航函数
const goBack = () => {
  router.go(-1);
};

const goToOrders = () => {
  router.push('/order');
};

const goToHome = () => {
  router.push('/');
};
</script>

<style scoped>
.checkout-view {
  min-height: 100vh;
  background: #f8fafc;
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #4a5568;
  cursor: pointer;
  margin-right: 15px;
}

.header h1 {
  margin: 0;
  font-size: 18px;
  color: #2d3748;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #4299e1;
  border-top: 4px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.checkout-content {
  padding: 0 20px 100px 20px;
}

.section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section h2 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #2d3748;
  font-weight: 600;
}

.add-address-btn {
  background: #4299e1;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.empty-address {
  text-align: center;
  padding: 30px;
  color: #718096;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.address-card {
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-card.active {
  border-color: #4299e1;
  background: #ebf8ff;
}

.address-info {
  flex: 1;
}

.contact {
  display: flex;
  gap: 15px;
  margin-bottom: 5px;
}

.name {
  font-weight: 600;
  color: #2d3748;
}

.phone {
  color: #718096;
}

.address {
  color: #4a5568;
  font-size: 14px;
}

.address-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.default-tag {
  background: #48bb78;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
}

.address-card.active .fa-check-circle {
  color: #4299e1;
  font-size: 18px;
}

.shop-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.shop-name {
  font-weight: 600;
  color: #2d3748;
}

.shop-address {
  color: #718096;
  font-size: 14px;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.item-row {
  display: flex;
  align-items: center;
  gap: 15px;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background-size: cover;
  background-position: center;
  flex-shrink: 0;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 5px;
  font-size: 14px;
  color: #2d3748;
}

.item-desc {
  margin: 0;
  font-size: 12px;
  color: #718096;
}

.item-quantity {
  color: #718096;
  font-size: 14px;
}

.item-price {
  font-weight: 600;
  color: #2d3748;
}

.price-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-row.discount {
  color: #48bb78;
}

.price-row.total {
  border-top: 1px solid #e2e8f0;
  padding-top: 10px;
  font-weight: 600;
  font-size: 16px;
}

.total-price {
  color: #e53e3e;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.payment-method {
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 15px;
}

.payment-method.active {
  border-color: #4299e1;
  background: #ebf8ff;
}

.method-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f7fafc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #4a5568;
}

.method-info {
  flex: 1;
}

.method-name {
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 2px;
}

.method-desc {
  font-size: 12px;
  color: #718096;
}

.payment-method.active .fa-check-circle {
  color: #4299e1;
  font-size: 18px;
}

.note-section textarea {
  width: 100%;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  resize: vertical;
  outline: none;
  transition: border-color 0.3s;
}

.note-section textarea:focus {
  border-color: #4299e1;
}

.checkout-footer {
  position: fixed;
  bottom: 60px;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #e2e8f0;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1001;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.price-summary {
  flex: 1;
}

.total-amount {
  display: flex;
  align-items: center;
  gap: 5px;
}

.amount {
  font-size: 18px;
  font-weight: 700;
  color: #e53e3e;
}

.submit-btn {
  background: #4299e1;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background: #3182ce;
}

.submit-btn:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 12px;
  max-width: 500px;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
}

.modal-header h3 {
  margin: 0;
  color: #2d3748;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #718096;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #4a5568;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 100%;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 10px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  border-color: #4299e1;
}

.form-group input[type="checkbox"] {
  width: auto;
  margin-right: 8px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 0 20px 20px;
}

.cancel-btn,
.save-btn,
.primary-btn,
.secondary-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn,
.secondary-btn {
  background: #e2e8f0;
  color: #4a5568;
}

.save-btn,
.primary-btn {
  background: #4299e1;
  color: white;
}

.cancel-btn:hover,
.secondary-btn:hover {
  background: #cbd5e0;
}

.save-btn:hover,
.primary-btn:hover {
  background: #3182ce;
}

.success-content {
  text-align: center;
  padding: 40px 20px;
}

.success-icon {
  font-size: 60px;
  color: #48bb78;
  margin-bottom: 20px;
}

.success-content h3 {
  margin: 0 0 15px;
  color: #2d3748;
}

.success-content p {
  margin: 5px 0;
  color: #718096;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .checkout-footer {
    bottom: 56px; /* 移动端底部导航栏高度 */
  }
  
  .checkout-content {
    padding: 0 20px 90px 20px; /* 移动端减少一些底部间距 */
  }
}
</style> 